#coding:utf-8
# @Time    : 2018/9/14 20:12
# @Author  : 0x007er
# @File    : testssh.py
# @Software: PyCharm
import paramiko,traceback,os,requests,demjson
def SSH_Exec_Command(IP,PASSWORD,COMMAND):
    try:
        # 检测PASSWORD是否为私钥文件
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if os.path.exists('privatekeys/' + PASSWORD) == True:
            private_key = paramiko.RSAKey.from_private_key_file('privatekeys/' + PASSWORD,password='admins')
            print 'privatekeys/' + PASSWORD
            # ssh.connect(hostname=IP, port=22, username='root', key_filename='privatekeys/' + PASSWORD,password='admins')
            ssh.connect(hostname=IP, port=22, username='root', pkey=private_key,password='admins')

        else:
            ssh.connect(hostname=IP, port=22, username='root', password=PASSWORD)
        stdin, stdout, stderr = ssh.exec_command(COMMAND)
        res, err = stdout.read(), stderr.read()
        result = res if res else err
        ssh.close()
        print(IP, PASSWORD, COMMAND, result.decode())
        return result.decode()
    except Exception as e:
        traceback.print_exc()
        print('SSH_Exec_Command:', IP, PASSWORD, COMMAND, e)
        return False
servers = demjson.decode(requests.get('http://185.10.68.223:5000/servers').text)
for server in servers:
    res = SSH_Exec_Command(server[1],'rsa','nohup apt-get -y install zmap > /var/www/html/iz.txt 2>&1 &')
    print res
